<template>
  <div>
    <heads />
    <Main :type="'form'">
      <el-form ref="form" label-width="170px" :model="form" :rules="form">
        <Title
          :title="'客户关系及分佣'"
          :msg="
            '以下项3天内修改仅可生效1次（当日24点前多次修改，以最后一次修改为准，次日凌晨5点后生效）'
          "
        ></Title>

        <el-form-item label="分佣归属">
          <el-radio-group v-model="form.hire_ascription">
            <el-radio :label="1">允许绑定，关系链优先</el-radio>
            <el-radio :label="2">不绑定，分享人优先</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="绑定场景"
          prop="bind_secen"
          :rules="{
            type: 'array',
            required: true,
            message: '请至少选择一个场景',
            trigger: 'blur'
          }"
        >
          <el-checkbox-group v-model="form.bind_secen">
            <el-checkbox label="1">访问并授权小程序</el-checkbox>
            <el-checkbox label="2">下单</el-checkbox>
            <el-checkbox label="3">注册成分销员</el-checkbox>
            <!-- <el-checkbox :label="4">关注公众号</el-checkbox> -->
          </el-checkbox-group>
          <span class="add-info"
            >客户在未绑定状态下符合勾选的1个节点即可绑定关系</span
          >
        </el-form-item>
        <el-form-item label="是否自动解绑">
          <el-radio-group v-model="form.hire_validity">
            <el-radio :label="1">不自动绑定</el-radio>
            <el-radio :label="2">有效期结束时</el-radio>
          </el-radio-group>
          <el-form-item
            v-if="form.hire_validity == 2"
            label="有效期"
            prop="validity"
            :rules="{
              required: true,
              message: '请输入有效期',
              trigger: 'blur'
            }"
            label-width="70px"
          >
            <el-input-number
              v-model="form.validity"
              :min="0"
              :precision="0"
              :step="1"
              :controls="false"
              size="medium"
              label="描述文字"
            ></el-input-number
            >&nbsp;&nbsp;天
            <span class="add-info"
              >在有效期内，客户每次访问带参链接或扫码，自动延长有效期</span
            >
          </el-form-item>
        </el-form-item>
        <el-form-item label="成本价保护">
          <el-switch
            v-model="form.cost_protect"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          {{ form.cost_protect ? "已开启" : "已关闭" }}
        </el-form-item>
        <el-form-item label="自购奖励">
          <el-checkbox v-model="form.self_buy"
            >分销员自身购买分销商品获得分佣</el-checkbox
          >
        </el-form-item>
        <el-form-item label="订单物流信息">
          <el-radio-group v-model="form.look_express">
            <el-radio :label="1">员工可查看客户订单物流信息</el-radio>
            <el-radio :label="2">员工不可查看客户订单物流信息</el-radio>
          </el-radio-group>
        </el-form-item>
        <Title
          :title="'分销员等级设置'"
          :msg="
            '以下项3天内修改仅可生效1次（当日24点前多次修改，以最后一次修改为准，次日凌晨5点后生效）'
          "
        ></Title>
        <el-form-item
          label="员工分销"
          prop="staff_bili"
          :rules="{
            required: true,
            message: '请输入分销比例',
            trigger: 'blur'
          }"
        >
          分销比例&nbsp;&nbsp;
          <el-input-number
            v-model="form.staff_bili"
            :min="0"
            :max="100"
            :precision="0"
            :step="1"
            :controls="false"
            size="medium"
            label="描述文字"
          ></el-input-number
          >&nbsp;%&nbsp;&nbsp;
          <span class="add-info">奖励比例不要超过商品原售价的50%</span>
        </el-form-item>
        <el-form-item label="客户分销">
          分销员等级条件
          <el-checkbox-group v-model="form.checkListFX">
            <el-checkbox :label="1" disabled>绑定客户数量</el-checkbox>
          </el-checkbox-group>
          <Table :data="tableData" style="width:80%;">
            <el-table-column label="等级名称">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.name"
                  placeholder="请输入内容"
                  size="medium"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              v-if="form.checkListFX.includes(1)"
              label="绑定客户人数（人）"
            >
              <template slot-scope="scope">
                <el-input
                  v-if="scope.$index > 0"
                  v-model="scope.row.grow_left"
                  size="medium"
                  style="width:80px;"
                  disabled
                ></el-input>

                <el-input
                  v-model="scope.row.grow_right"
                  size="medium"
                  style="width:80px;"
                  @blur="growthTag(scope.row.grow_right, scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="默认比例（%）">
              <template slot-scope="scope">
                分销比例&nbsp;&nbsp;
                <el-input-number
                  v-model="scope.row.bili"
                  :min="0"
                  :max="100"
                  :precision="0"
                  :step="1"
                  :controls="false"
                  label="描述文字"
                  size="medium"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80px" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.$index == tableData.length - 1"
                  type="text"
                  @click="delLevel(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </Table>
          <div
            style="margin-top:10px;font-size:12px;"
            class="add-form-hintColor"
          >
            <el-button plain :disabled="tableData.length >= 5" @click="addLevel"
              >添加等级</el-button
            >
            &emsp; 会员等级可添加5级
          </div>
        </el-form-item>
      </el-form>
    </Main>
    <Footer>
      <el-button type="primary" @click="submit">保 存</el-button>
    </Footer>
  </div>
</template>
<script>
import { HIRESETTING, DEFAULTBILI } from "../service";

export default {
  components: {
    heads: () => import("./component/heads")
  },
  data() {
    return {
      send: "",
      options: "second",
      radius: 1,
      form: {
        hire_ascription: 1,
        bind_secen: [],
        hire_validity: 1,
        validity: 0,
        cost_protect: false,
        self_buy: false,
        radio: 1,
        staff_bili: 1,
        checkListFX: [1],
        tableData: [],
        look_express: 1
      },
      tableData: []
    };
  },
  created() {
    this.getData();
  },
  methods: {
    addLevel() {
      let arr = this.tableData;
      if (arr.length < 10) {
        arr.push({
          distribute_lv_id: 0,
          name: "",
          grow_left: 0,
          grow_right: 0,
          bili: 0
        });
      }
      if (arr.length > 1) {
        arr[arr.length - 2].grow_right = arr[arr.length - 2].grow_left + 1;
        arr[arr.length - 1].grow_left = arr[arr.length - 2].grow_right + 1;
        arr[arr.length - 1].grow_right = arr[arr.length - 1].grow_left + 1;
      }
    },
    delLevel(i) {
      let arr = this.tableData;
      if (i >= 1) {
        arr.splice(i, 1);
        arr[i].grow_left = arr[i - 1].grow_right + 1;
      } else {
        arr.splice(i, 1);
        if (arr.length >= 1) {
          arr[0].grow_left = 0;
        }
      }
    },
    growthTag(e, i) {
      if (isNaN(parseInt(e))) {
        this.tableData[i].grow_right = 0;
      } else {
        this.tableData[i].grow_right = parseInt(e);
      }
      let arr = this.tableData;
      arr.forEach((ele, idx) => {
        if (idx > i) {
          if (ele.grow_right <= ele.grow_left) {
            ele.grow_right = parseInt(ele.grow_left) + 1;
          }
          if (ele.grow_right > ele.grow_left) {
            ele.grow_left = parseInt(arr[idx - 1].grow_right) + 1;
          }
          if (ele.grow_right <= arr[idx - 1].grow_right) {
            ele.grow_right = parseInt(ele.grow_left) + 1;
          }
        } else {
          if (arr[i].grow_right <= arr[i].grow_left) {
            arr[i].grow_right = parseInt(arr[i].grow_left) + 1;
          }
        }
      });
    },
    async submit() {
      await this.$refs["form"].validate(valid => {
        if (valid) {
          let json = JSON.parse(JSON.stringify(this.tableData));
          json.forEach((ele, i) => {
            ele.members = ele.grow_right;
            ele.lv = i + 1;
            delete ele.grow_left;
            delete ele.grow_right;
          });
          HIRESETTING({
            flag: "save",
            hire_ascription: this.form.hire_ascription,
            bind_secen: this.form.bind_secen.join(","),
            hire_validity: this.form.hire_validity,
            cost_protect: this.form.cost_protect ? 1 : 0,
            self_buy: this.form.self_buy ? 1 : 0,
            staff_bili: this.form.staff_bili,
            validity: this.form.validity,
            look_express: this.form.look_express,
            json: JSON.stringify(json)
          }).then(({ code, msg }) => {
            if (code === 200) {
              this.$emit("out");
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        } else {
          return false;
        }
      });
    },
    async getData() {
      await HIRESETTING().then(({ code, data, msg }) => {
        if (code === 200) {
          this.form.hire_ascription = data.hire_ascription;
          this.form.bind_secen = data.bind_secen.split(",");
          this.form.hire_validity = data.hire_validity;
          this.form.cost_protect = data.cost_protect === 1;
          this.form.self_buy = data.self_buy === 1;
          this.form.staff_bili = data.staff_bili;
          this.form.look_express = data.look_express;
          this.form.validity = data.validity;
        }
        this.$message({
          message: msg,
          type: code === 200 ? "success" : "error"
        });
      });
      await DEFAULTBILI().then(res => {
        let { code, data } = res;
        if (code === 200) {
          data.forEach((ele, i) => {
            if (i > 0) {
              ele.grow_left = data[i - 1].grow_right + 1;
            } else {
              ele.grow_left = 0;
            }
            ele.grow_right = ele.members;
          });
          this.tableData = data;
        }
        // this.$message({
        //   message: msg,
        //   type: code === 200 ? 'success' : 'error'
        // })
      });
    }
  }
};
</script>
